//
//  MeSetViewController.m
//  DBAChain
//
//  Created by Mxionlly on 2018/9/8.
//  Copyright © 2018年 Evan. All rights reserved.
//

#import "MeSetViewController.h"
#import "GeneralTool.h"
#import "DWEditUserInfoCell.h"
#import "MeModifyViewController.h"
#import "MeSecurityViewController.h"
#import "MeAuthenticationViewController.h"
#import "taskUserManagerService.h"
#import "NetworkManager.h"
#import "MeCallViewController.h"
#import "MeAutStatusViewController.h"
#import "MeAutCompleteViewController.h"
#import "MeModifyNameViewController.h"
#import "dataGeneralAuthUser.h"
#import "LoginNavigationController.h"
#import "MeModifyMobileViewController.h"

@interface MeSetViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,strong)UITableView    *tableView;
@property (nonatomic,strong)NSArray        *cellArray;
@property (nonatomic,strong)dataGeneralAuthInfo *dataModel;

@property (nonatomic,strong)UIImagePickerController *imagePicker;

@end

@implementation MeSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"个人设置";
   
    self.cellArray = @[@[@"头像",@"昵称",@"修改登录密码",@"修改支付密码",@"修改手机号",@"安全认证",@"实名认证",@"版本号"],@[@"icon_login_user",@"icon_me_edit",@"icon_login_lock",@"icon_lock",@"icon_register_phone",@"icon_me_aut_shield",@"icon_me_aut_card",@"icon_v"]];
    [self.view addSubview:self.tableView];
    [self loadData];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setBlackStatus:YES];
    [self.tableView reloadData];
    self.hidesBottomBarWhenPushed = NO;
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = NO;
}

-(void)loadData{
    [taskUserManagerService getUserAuthen:nil success:^(dataGeneralAuthUser *response, BOOL success) {
        [DKProgressHUD dismiss];
        if (success) {
            if ([response.data count] > 0) {
                self.dataModel = [dataGeneralAuthInfo mj_objectWithKeyValues:response.data[0]];
            }
        }else{
            [DKProgressHUD showErrorWithStatus:response.message];
        }
    } failture:^(NSError *error, NSString *strDescription) {
        [DKProgressHUD dismiss];
        [DKProgressHUD showErrorWithStatus:strDescription];
    }];
}

#pragma mark - init
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, distanceHeight, KScreenWidth, KScreenHeight-distanceHeight) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor  = [UIColor clearColor];
        _tableView.scrollEnabled = YES;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

#pragma mark - UITableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.cellArray[0] count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DWEditUserInfoCell *cell = [DWEditUserInfoCell cellWithTableView:tableView];
    cell.lbtitle.text =self.cellArray[0][indexPath.row];
    cell.rightImageView.image = [UIImage imageNamed:self.cellArray[1][indexPath.row]];
    cell.headerImg.hidden = YES;
    cell.lbcontent.hidden = NO;
    if (indexPath.section == 0 ) {
        if (indexPath.row == 0) {
            
            //url请求实在UI主线程中进行的
            NSString *encodeStr = [[UserCenter shareCenter].user.imageUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];            
            [cell.headerImg sd_setImageWithURL:[NSURL URLWithString:encodeStr] placeholderImage:[UIImage imageNamed:@"icon_icon"]];
            
            cell.headerImg.hidden = NO;
            cell.lbcontent.hidden = YES;
        }else if (indexPath.row == 1){
            cell.lbcontent.text = [UserCenter shareCenter].user.userName;
        }
    }
    if (indexPath.row == 7) {
        //判断你需要更新的业务逻辑
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
         NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        cell.lbcontent.text = [NSString stringWithFormat:@"version %@",app_Version];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        [GeneralTool showActionSheetWithTitle:@"" firstActionTitle:@"拍照" secondActionTitle:@"从手机相册选择" cancelActionTitle:@"取消" controller:self actionBlock:^(id aResponseObject, NSError *anError) {
            [self chooseImagePicker:[aResponseObject integerValue]];
        }];
    }else if (indexPath.row == 1){
        [self.navigationController pushViewController:[MeModifyNameViewController new] animated:YES];
    }else if (indexPath.row == 2 || indexPath.row == 3){
        [self.navigationController pushViewController:[[MeModifyViewController alloc]initWithType:indexPath.row == 2 ? 0 : 1] animated:YES];
    }else if (indexPath.row == 4){
        [self.navigationController pushViewController:[MeModifyMobileViewController new] animated:YES];
    }else if (indexPath.row == 5){
        [self.navigationController pushViewController:[MeSecurityViewController new] animated:YES];
    }else if (indexPath.row == 6){
        if ([[UserCenter shareCenter].user.IsIdentification isEqualToString:@"20060001"]) {
            [self.navigationController pushViewController:[MeAutStatusViewController new] animated:YES];
        }else if ([[UserCenter shareCenter].user.IsIdentification isEqualToString:@"20060002"]){
            [self.navigationController pushViewController:[[MeAutCompleteViewController alloc]initWithModel:self.dataModel] animated:YES];
        }else {
            [self.navigationController pushViewController:[MeAuthenticationViewController new] animated:YES];
        }
    }
}

#pragma mark - 相片选择
-(void)chooseImagePicker:(NSInteger )index{

        NSUInteger sourceType = 0;
        // 判断系统是否支持相机
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            imagePickerController.delegate = self; //设置代理
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType = sourceType; //图片来源
            if (index == 0) {
                return;
            }else if (index == 1) {
                //拍照
                sourceType = UIImagePickerControllerSourceTypeCamera;
                imagePickerController.sourceType = sourceType;
                [self presentViewController:imagePickerController animated:YES completion:nil];
            }else if (index == 2){
                //相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                imagePickerController.sourceType = sourceType;
                [self presentViewController:imagePickerController animated:YES completion:nil];
            }
        }else {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePickerController.sourceType = sourceType;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

    [self fileUpload:image];
    if (@available(iOS 11.0, *)){
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    //处理完毕，回到个人信息页面
    [self dismissViewControllerAnimated:YES completion:nil];
    [picker dismissViewControllerAnimated:YES completion:NULL];
}


- (void)fileUpload:(UIImage*)filePath {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",@"text/plain"]];
    
    [manager.requestSerializer setValue:[UserCenter shareCenter].authToken forHTTPHeaderField:@"token"];
    [manager.requestSerializer setValue:[UserCenter shareCenter].authToken forHTTPHeaderField:@"access_token"];
    [manager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"source"];
    [manager.requestSerializer setValue:@"APP" forHTTPHeaderField:@"User-Agent"];
    NSString *url = [NSString stringWithFormat:@"%@%@", YBaseURLString,DEF_API_uploadImg];
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setValue:@(1) forKey:@"uploadtype"];
    NSLog(@"上传图片入参：%@%@",DEF_API_uploadImg,dict);
    url = [NSString stringWithFormat:@"%@?uploadtype=2",url];
    [manager POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDate *date = [NSDate date];
        NSDateFormatter *formormat = [[NSDateFormatter alloc]init];
        [formormat setDateFormat:@"HHmmss"];
        NSString *dateString = [formormat stringFromDate:date];
        
        NSString *fileName = [NSString  stringWithFormat:@"%@.png",dateString];
        NSData *imageData = UIImageJPEGRepresentation(filePath, 1);
        double scaleNum = (double)300*1024/imageData.length;
        if(scaleNum <1){
            imageData = UIImageJPEGRepresentation(filePath, scaleNum);
        }else{
            imageData = UIImageJPEGRepresentation(filePath, 0.1);
        }
        [formData  appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
        [DKProgressHUD showLoadingWithStatus:@"正在上传..."];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [DKProgressHUD dismiss];
        NSDictionary *datas = responseObject;
        NSString *statusCode = [datas objectForKey:@"statusCode"];
        if (![[NSString stringWithFormat:@"%@",statusCode]  isEqualToString: @"200"]) {
            NSString *strError = [datas objectForKey:@"message"];
            [[UIAlertController alloc] alertTitle:@"上传失败" alertMessage:strError leftCancelTitle:nil leftCancel:nil rightTitle:@"确定" rightOK:^(UIAlertAction *action) {
                
            }];
            return ;
        }
        
        NSString *strUrl = [datas objectForKey:@"data"];
        [self uploadUserImg:strUrl];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [DKProgressHUD showErrorWithStatus:@"头像修改失败"];
    }];
}

-(void)uploadUserImg:(NSString*)url{    
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setValue:url forKey:@"headUrl"];
    [dict setValue:[UserCenter shareCenter].user.pid forKey:@"userId"];
    [taskUserManagerService getUserUploadImg:dict success:^(BaseModel *response, BOOL success) {
        [DKProgressHUD dismiss];
        if (success) {
            //刷新用户数据后刷新本地tableview
            [[UserCenter shareCenter]refreshProfiles:^(dataGetUserInfo *profile) {
                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
            }];
        }else{
            [DKProgressHUD showErrorWithStatus:response.message];
        }
    } failture:^(NSError *error, NSString *strDescription) {
        [DKProgressHUD dismiss];
        [DKProgressHUD showErrorWithStatus:strDescription];
    }];
}


#pragma mark - loginOut
-(void)loginOut
{
    [[UserCenter shareCenter]logout:^(BOOL suc,NSString *error) {
        if (suc) {
            
            LoginNavigationController *login = [[LoginNavigationController alloc]init];
            [self presentViewController:login animated:YES completion:nil];
        }else{
            [DKProgressHUD showErrorWithStatus:error];
        }
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
